#include "uart_config.h"
#include "Drv_W25Q64.h" 
#include <string.h>
#include <stdio.h>

#define UART_CONFIG_MAGIC 0x55434F4E  // 'UCON' 魔术字校验

typedef struct
{
    uint32_t magic;
    UartConfig_TypeDef config_array[UART_CONFIG_COUNT];
    uint32_t crc;  // 简单校验用
} UartConfigFlashWrap;

UartConfig_TypeDef local_uart_config[UART_CONFIG_COUNT];

static uint32_t simple_crc32(uint8_t* data, uint32_t length)
{
    uint32_t crc = 0;
    for(uint32_t i = 0; i < length; i++)
    {
        crc += data[i];
    }
    return crc;
}

void LoadUartConfigFromFlash(void) {
    UartConfigFlashWrap wrap;
    //Flash_Read(SOCKET_CONFIG_ADDRESS, (uint8_t*)&wrap, sizeof(wrap));
	  W25Q64_ReadData(UART_CONFIG_ADDRESS, (uint8_t *)&wrap, sizeof(wrap));  
		//printf("=== Uart Config Load from FLash magic is %08X ===\r\n",wrap.magic );
    if (wrap.magic == UART_CONFIG_MAGIC)
    {
			  //printf("=== Uart Config Load from FLash magic is %08X ===\r\n",wrap.magic );
        uint32_t crc = simple_crc32((uint8_t*)&wrap.config_array, sizeof(local_uart_config));
        if (crc == wrap.crc)
        {
					  printf("=== Uart Config Loaded from Flash ===\r\n");
            //local_socket_config = wrap.config;
					  memcpy(local_uart_config, wrap.config_array, sizeof(local_uart_config));
            return;
        }
    }
		printf("=== Uart Config Loaded Default ===\r\n");
    // 无效数据，恢复默认
    ResetUartConfigToDefault();
}

void SaveUartConfigToFlash(void)
{
    UartConfigFlashWrap wrap;
    wrap.magic = UART_CONFIG_MAGIC;
    //wrap.config = local_socket_config;
	  memcpy(wrap.config_array, local_uart_config, sizeof(local_uart_config));
    wrap.crc = simple_crc32((uint8_t*)&wrap.config_array, sizeof(local_uart_config));
		printf("=== Save Uart Config jisuan crc is %d ===\r\n",wrap.crc );
	  W25Q64_SectorErase(UART_CONFIG_ADDRESS);	
    W25Q64_PageProgram(UART_CONFIG_ADDRESS, (uint8_t*)&wrap, sizeof(wrap)); 

}

void ResetUartConfigToDefault(void) {
	  for (int i = 0; i < UART_CONFIG_COUNT; ++i)
    {
				local_uart_config[i].BaudRate = BAUD_115200;
				local_uart_config[i].DataBits = DATA_BITS_8;
				local_uart_config[i].StopBits = STOP_BITS_1;
			  local_uart_config[i].Parity   = UART_PARITY_NONE;
		}
    SaveUartConfigToFlash();
}
